package DRC;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import DRC.DRModbus.DRModbus_RTU_Slave;
import DRC.DRModbus.DRModbus_TCP_Slave;
import DRCOMM.dr_ajax_answer;
import DRCOMM.record_data_set;
import DRCOMM.DRHTTP_API;
import DRCOMM.DR_SESSION;
import DRCOMM.FJW_URI;

public class channel{

    public int channel_id=-1;
    public String name="";
    public String host_ip="";
    public int port=-1;
    public int protocol=-1;
    public int data_type=0;
    public int type=0;              // type=0：通用服务通道，输出值为本地寄存器结合过滤器
                                    // type=1：转发通道，输出值为采集通道数据点值
                                    // type=2/其他情况，判定为多通道，对应采集通道的具体映射数据点

    public int channel4collect_id=-1;
    public String path="";
    public String filename="";
    public String com="";
    public int band_rate=-1;
    public int parity=-1;
    public int stop=-1;
    public int enable=1;
    public Date create_time=new Date();

    public DRCDB drcdb;
    public final static int data_count=1024;
    public ArrayList<dataItem> dataItems=null;
    public channel_data_filter cdf=null;
    public ArrayList<dataItem4collect> d4cs=new ArrayList<dataItem4collect>();
    public channel4collect c4c=null;
    public static ArrayList<channel> channels=null;

    private static Map<String,Thread> channel_run_list=new HashMap<String,Thread>();

    public channel(DRCDB drcdb){
        this.drcdb=drcdb;
    }

    public channel(DRCDB drcdb,String name,String host_ip){
        this.drcdb=drcdb;
        this.name=name;
        this.host_ip=host_ip;
    }

    public channel(int channel_id,String name,String host_ip,int port,
        int protocol){
        this.channel_id=channel_id;
        this.name=name;
        this.host_ip=host_ip;
        this.port=port;
        this.protocol=protocol;
    }

    public channel(int channel_id,String name,String host_ip,int port,
        int protocol,int data_type,int type,int channel4collect_id,
        String path,String filename,String com,int band_rate,int parity,
        int stop,int enable,Date create_time){
        this.channel_id=channel_id;
        this.name=name;
        this.host_ip=host_ip;
        this.port=port;
        this.protocol=protocol;
        this.data_type=data_type;
        this.type=type;
        this.channel4collect_id=channel4collect_id;
        this.path=path;
        this.filename=filename;
        this.com=com;
        this.band_rate=band_rate;
        this.parity=parity;
        this.stop=stop;
        this.enable=enable;
        this.create_time=create_time;
    }

    public void report(){
        System.out.println("channel_id="+this.channel_id);
        System.out.println("name="+this.name);
        System.out.println("host_ip="+this.host_ip);
        System.out.println("port="+this.port);
        System.out.println("protocol="+this.protocol);
        System.out.println("data_type="+this.data_type);
        System.out.println("type="+this.type);
        System.out.println("channel4collect_id="+this.channel4collect_id);
        System.out.println("path="+this.path);
        System.out.println("filename="+this.filename);
        System.out.println("com="+this.com);
        System.out.println("band_rate="+this.band_rate);
        System.out.println("parity="+this.parity);
        System.out.println("stop="+this.stop);
        System.out.println("enable="+this.enable);
        System.out.println("create_time="+this.create_time);
    }

    public void set_channel_id(int channel_id){
        this.channel_id=channel_id;
    }

    public void set_path(String path,String filename){
        this.path=path;
        this.filename=filename;
    }

    public void set_com(String com,int band_rate){
        this.com=com;
        this.band_rate=band_rate;
    }

    public record_data_set read_channels(){
        DRCDB db=this.drcdb;
        String sqlstr="select * from channel";
        record_data_set rds=db.executeQuerySQL(sqlstr);
        return rds;
    }

    /**
     * 关联WEB API列表
     * @param api_lists
     * @param drcdb
     */
    public static void associate_actions(List<DRHTTP_API> api_lists,DRCDB drcdb) throws ClassNotFoundException{
        @SuppressWarnings("unchecked")
        Class<?> CLS=(Class<channel>) Class.forName("DRC.channel");
        for(Method method:CLS.getDeclaredMethods()){
            FJW_URI fjw_uri=method.getAnnotation(FJW_URI.class);
//            System.out.println(method.toString());
            if(fjw_uri!=null){
//                System.out.println(method.toString());
//                System.out.println(fjw_uri.value());
                try {
                    api_lists.add((DRHTTP_API)method.invoke(CLS,drcdb, fjw_uri.value()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @FJW_URI(value ="channel/channelList")
    public static DRHTTP_API channel_list(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String page=this.get_parameters(parameters,"page");
                String limit=this.get_parameters(parameters,"limit");
                DRCDB db=drcdb;
                int pagesize;
                int current_page;
                if(page.equals(""))current_page=1;
                else current_page=Integer.parseInt(page);
                if(limit.equals(""))pagesize=10;
                else pagesize=Integer.parseInt(limit);
                String sqlstr="select channel_id,name,host_ip,port,com,band_rate,protocol,enable from channel order by channel_id";
                sqlstr+=String.format(" limit %d,%d",pagesize*(current_page-1),pagesize);
                record_data_set rds=db.executeQuerySQL(sqlstr);
                content=record_data_set.get_answer_json_str(0,"",rds);
                return content;
            }
        };
    }

    @FJW_URI(value ="channel/readChannel")
    public static DRHTTP_API read_channel(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                DRCDB db=drcdb;
                String sqlstr="select channel_id,name,host_ip,port,protocol,data_type,type,channel4collect_id,path,filename,com,band_rate,parity,stop,enable from channel";
                sqlstr+=String.format(" where channel_id=%s",channel_id);
                record_data_set rds=db.executeQuerySQL(sqlstr);
                content=record_data_set.get_answer_json_str(0,"",rds);
                return content;
            }
        };
    }

    @FJW_URI(value ="channel/saveChannel")
    public static DRHTTP_API save_channel(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                String name=this.get_parameters(parameters,"name");
                String host_ip=this.get_parameters(parameters,"host_ip");
                String port=this.get_parameters(parameters,"port");
                String protocol=this.get_parameters(parameters,"protocol");
                String data_type=this.get_parameters(parameters,"data_type");
                String type=this.get_parameters(parameters,"type");
                String channel4collect=this.get_parameters(parameters,"channel4collect");
                String path=this.get_parameters(parameters,"path");
                String filename=this.get_parameters(parameters,"filename");
                String com=this.get_parameters(parameters,"com");
                String band_rate=this.get_parameters(parameters,"band_rate");
                String parity=this.get_parameters(parameters,"parity");
                String stop=this.get_parameters(parameters,"stop");
                String enable=this.get_parameters(parameters,"enable");
                DRCDB db=drcdb;
                String sqlstr;
                boolean result=false;
                enable=(enable.length()>0)?"1":"0";
                if(channel4collect.equals(""))channel4collect="0";
                if(channel_id==null||channel_id==""){
                    Date now=new Date();
                    SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
                    sqlstr="insert into channel(name,host_ip,port,protocol,data_type,type,channel4collect_id,path,filename,com,band_rate,parity,stop,enable,create_time) ";
                    sqlstr+=String.format(" values('%s','%s',%s,%s,%s,%s,%s,'%s','%s','%s',%s,%s,%s,%s,'%s')",name,host_ip,port,protocol,data_type,type,channel4collect,path,filename,com,band_rate,parity,stop,enable,ft.format(now));
                }else{
                    sqlstr="update channel";
                    sqlstr+=String.format(" set name='%s'" , name);
                    sqlstr+=String.format(",host_ip='%s'" , host_ip);
                    sqlstr+=String.format(",port=%s" , port);
                    sqlstr+=String.format(",protocol=%s" , protocol);
                    sqlstr+=String.format(",data_type=%s" , data_type);
                    sqlstr+=String.format(",type=%s" , type);
                    sqlstr+=String.format(",channel4collect_id=%s" , channel4collect);
                    sqlstr+=String.format(",path='%s'" , path);
                    sqlstr+=String.format(",filename='%s'" , filename);
                    sqlstr+=String.format(",com='%s'" , com);
                    sqlstr+=String.format(",band_rate=%s" , band_rate);
                    sqlstr+=String.format(",enable=%s" , enable);
                    sqlstr+=String.format(" where channel_id=%s" , channel_id);
                }
                result=db.executeUpdateSQL(sqlstr);
                if(result){
                    content=dr_ajax_answer.sample_json_string(0,"");
                }else{
                    content=dr_ajax_answer.sample_json_string(1,"保存失败！");
                }
                return content;
            }
        };
    }

    @FJW_URI(value ="channel/delChannel")
    public static DRHTTP_API del_channel(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                boolean result=false;
                DRCDB db=drcdb;
                String sqlstr;
                if(channel_id=="1"){
                    content=dr_ajax_answer.sample_json_string(1,"通道1不能删除！");
                }else{
                    sqlstr="delete from channel";
                    sqlstr+=String.format(" where channel_id=%s" , channel_id);
                    result=db.executeUpdateSQL(sqlstr);
                    sqlstr="delete from dataItem";
                    sqlstr+=String.format(" where channel_id=%s" , channel_id);
                    result=db.executeUpdateSQL(sqlstr);
                }
                if(result){
                    content=dr_ajax_answer.sample_json_string(0,"");
                }else{
                    content=dr_ajax_answer.sample_json_string(1,"保存失败！");
                }
                return content;
            }
        };
    }

    @FJW_URI(value ="channel/channel_data_filter_data_list")
    public static DRHTTP_API channel_data_filter_data_list(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                String page=this.get_parameters(parameters,"page");
                String limit=this.get_parameters(parameters,"limit");
                DRCDB db=drcdb;
                int pagesize;
                int current_page;
                if(page.equals(""))current_page=1;
                else current_page=Integer.parseInt(page);
                if(limit.equals(""))pagesize=10;
                else pagesize=Integer.parseInt(limit);
                String sqlstr="select cdf.channel_data_filter_id,c.name,c.host_ip,c.port,c.protocol,cdf.register_type,cdf.filter ";
                sqlstr+=" from channel_data_filter cdf left join channel c on cdf.channel_id=c.channel_id";
                sqlstr+=String.format(" where cdf.channel_id=%s",channel_id);
                sqlstr+=" order by cdf.channel_data_filter_id";
                sqlstr+=String.format(" limit %d,%d",pagesize*(current_page-1),pagesize);
                record_data_set rds=db.executeQuerySQL(sqlstr);
                content=record_data_set.get_answer_json_str(0,"",rds);
                return content;
            }
        };
    }

    @FJW_URI(value ="channel/readChannel_data_filter")
    public static DRHTTP_API read_channel_data_filter(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_data_filter_id=this.get_parameters(parameters,"channel_data_filter_id");
                DRCDB db=drcdb;
                String sqlstr="select cdf.channel_data_filter_id,c.name,c.host_ip,c.port,c.protocol,cdf.register_type,cdf.filter ";
                sqlstr+=" from channel_data_filter cdf left join channel c on cdf.channel_id=c.channel_id";
                sqlstr+=String.format(" where cdf.channel_data_filter_id=%s",channel_data_filter_id);
                record_data_set rds=db.executeQuerySQL(sqlstr);
                content=record_data_set.get_answer_json_str(0,"",rds);
                return content;
            }
        };
    }

    @FJW_URI(value ="channel/saveChannel_data_filter")
    public static DRHTTP_API save_channel_data_filter(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_data_filter_id=this.get_parameters(parameters,"channel_data_filter_id");
                String channel_id=this.get_parameters(parameters,"channel_id");
                String register_type=this.get_parameters(parameters,"register_type");
                String filter=this.get_parameters(parameters,"filter");
                DRCDB db=drcdb;
                String sqlstr;
                boolean result=false;
                if(channel_data_filter_id==null||channel_data_filter_id==""){
                    sqlstr="insert into channel_data_filter(channel_id,register_type,filter) ";
                    sqlstr+=String.format(" values(%s,%s,'%s')",channel_id,register_type,filter);
                }else{
                    sqlstr="update channel_data_filter";
                    sqlstr+=String.format(" set channel_id=%s" , channel_id);
                    sqlstr+=String.format(",register_type=%s" , register_type);
                    sqlstr+=String.format(",filter='%s'" , filter);
                    sqlstr+=String.format(" where channel_data_filter_id=%s" , channel_data_filter_id);
                }
                result=db.executeUpdateSQL(sqlstr);
                if(result){
                    content=dr_ajax_answer.sample_json_string(0,"");
                }else{
                    content=dr_ajax_answer.sample_json_string(1,"保存失败！");
                }
                return content;
            }
        };
    }
    
    @FJW_URI(value ="channel/del_channel_data_filter")
    public static DRHTTP_API del_channel_data_filter(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_data_filter_id=this.get_parameters(parameters,"channel_data_filter_id");
                boolean result=false;
                DRCDB db=drcdb;
                String sqlstr;
                sqlstr="delete from channel_data_filter";
                sqlstr+=String.format(" where channel_data_filter_id=%s" , channel_data_filter_id);
                result=db.executeUpdateSQL(sqlstr);
                if(result){
                    content=dr_ajax_answer.sample_json_string(0,"");
                }else{
                    content=dr_ajax_answer.sample_json_string(1,"保存失败！");
                }
                return content;
            }
        };
    }

    public static record_data_set readChannelDataFilters(DRCDB drcdb,int channel_id){
        if(channel_id==1)return null;
        String sqlstr="select cdf.channel_data_filter_id,c.name,c.host_ip,c.port,c.protocol,cdf.register_type,cdf.filter ";
        sqlstr+=" from channel_data_filter cdf left join channel c on cdf.channel_id=c.channel_id";
        sqlstr+=" where cdf.channel_id="+channel_id;
        sqlstr+=" order by cdf.channel_data_filter_id";
        return drcdb.executeQuerySQL(sqlstr);
    }

    @FJW_URI(value ="channel/checkChannelState")
    public static DRHTTP_API checkChannelState(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                if(channel_run_list.containsKey("channel_"+channel_id)){
                    content=dr_ajax_answer.sample_json_string(0,"通道已运行");
                }else{
                    content=dr_ajax_answer.sample_json_string(1,"通道未运行");
                }
                return content;
            }
        };
    }

    public static ArrayList<channel> read_channels(DRCDB drcdb,ArrayList<channel4collect> chs4c){
        channels=new ArrayList<channel>();
        String sqlstr="select channel_id,name,host_ip,port,protocol,data_type,type,channel4collect_id,path,filename,com,band_rate,parity,stop,enable,create_time from channel";
        String sqlstr_df;
        String sqlstr_d2c;
        record_data_set rds=drcdb.executeQuerySQL(sqlstr);
        // for(Map<String,String> data:rds.datas){
        for(int i=0;i<rds.datas.size();i++){
            int channel_id=Integer.parseInt(rds.datas.get(i).get("channel_id"));
            String name=rds.datas.get(i).get("name");
            String host_ip=rds.datas.get(i).get("host_ip");
            int port=Integer.parseInt(rds.datas.get(i).get("port"));
            int protocol=Integer.parseInt(rds.datas.get(i).get("protocol"));
            int data_type=Integer.parseInt(rds.datas.get(i).get("data_type"));
            int type=Integer.parseInt(rds.datas.get(i).get("type"));
            int channel4collect_id=Integer.parseInt(rds.datas.get(i).get("channel4collect_id"));
            String path=rds.datas.get(i).get("path");
            String filename=rds.datas.get(i).get("filename");
            String com=rds.datas.get(i).get("com");
            int band_rate=Integer.parseInt(rds.datas.get(i).get("band_rate"));
            int parity=Integer.parseInt(rds.datas.get(i).get("parity"));
            int stop=Integer.parseInt(rds.datas.get(i).get("stop"));
            int enable=(int)Float.parseFloat(rds.datas.get(i).get("enable"));
            SimpleDateFormat ft=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date create_time=new Date();
            try {
                create_time = ft.parse(rds.datas.get(i).get("create_time"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            channel ch=new channel(channel_id,name,host_ip,port,protocol,data_type,
                type,channel4collect_id,path,filename,com,band_rate,parity,stop,
                enable,create_time);
            if(i==0){
                // 通道0（channel_id=1）为默认的服务通道，通过该通道访问本地寄存器
                // 初始化本地寄存器列表
                // 本地寄存器根据data_count设定数量，共4种寄存器类型，对应Modbus的4种寄存器
                dataItem[] dataItems=new dataItem[channel.data_count*4];
                for(int di=0;di<(channel.data_count);di++){
                    dataItems[di+channel.data_count*0]=new dataItem(di+channel.data_count*0,1,1,1,di,di,"data-"+(1)+"-"+di,1);
                    dataItems[di+channel.data_count*0].value=di%2;
                    dataItems[di+channel.data_count*1]=new dataItem(di+channel.data_count*1,1,1,2,di,di+channel.data_count*1,"data-"+(2)+"-"+di,1);
                    dataItems[di+channel.data_count*1].value=di%2;
                    dataItems[di+channel.data_count*2]=new dataItem(di+channel.data_count*2,1,1,3,di,di+channel.data_count*2,"data-"+(3)+"-"+di,1);
                    dataItems[di+channel.data_count*2].value=di;
                    dataItems[di+channel.data_count*3]=new dataItem(di+channel.data_count*3,1,1,4,di,di+channel.data_count*3,"data-"+(4)+"-"+di,1);
                    dataItems[di+channel.data_count*3].value=di;
                }
                ch.dataItems=new ArrayList<>(Arrays.asList(dataItems));
            }else{
                // 除默认服务通道外，其他通道均需读取是否存在过滤器
                // 对于存在过滤器的通道，只能访问符合过滤条件的数据点
                sqlstr_df="select cdf.channel_data_filter_id,c.name,c.host_ip,c.port,c.protocol,cdf.register_type,cdf.filter ";
                sqlstr_df+=" from channel_data_filter cdf left join channel c on cdf.channel_id=c.channel_id";
                sqlstr_df+=" where cdf.channel_id="+channel_id;
                sqlstr_df+=" order by cdf.channel_data_filter_id";
                record_data_set rds_df=drcdb.executeQuerySQL(sqlstr_df);
                if(rds_df.datas.size()>0){
                    int channel_data_filter_id=Integer.parseInt(rds_df.datas.get(0).get("channel_data_filter_id"));
                    int register_type=Integer.parseInt(rds_df.datas.get(0).get("register_type"));
                    String filter=rds_df.datas.get(0).get("filter");
                    ch.cdf=new channel_data_filter(channel_data_filter_id,channel_id,register_type,filter);
                }
                // 根据type判断通道类型
                // type=0：通用服务通道，输出值为本地寄存器结合过滤器
                // type=1：转发通道，输出值为采集通道数据点值
                // type=2/其他情况，判定为多通道，对应采集通道的具体映射数据点
                if(type==1){
                    for(channel4collect c4c:chs4c){
                        if(c4c.channel_id==ch.channel4collect_id){
                            ch.c4c=c4c;
                        }
                    }
                }else{
                    // 查询是否存在服务通道对应多通道数据点
                    sqlstr_d2c="select * from dataItem2channel where channel_id="+channel_id;
                    record_data_set rds_d2c=drcdb.executeQuerySQL(sqlstr_d2c);
                    // 为映射多通道的服务通道关联数据点
                    // 查找标志，当找到数据点时为真
                    boolean find_mark;
                    // 逐个扫描所有该通道的映射数据点
                    for(Map<String,String> data:rds_d2c.datas){
                        find_mark=false;
                        // 逐个采集通道扫描
                        for(channel4collect ch4c:chs4c){
                            // 在采集通道中逐个扫描
                            for(dataItem4collect d4c:ch4c.ds4c){
                                if(d4c.dataItem_id==Integer.parseInt(data.get("dataItem_id"))){
                                    ch.d4cs.add(d4c);
                                    d4c.report();
                                    find_mark=true;
                                    break;
                                }
                            }
                            if(find_mark)break;
                        }
                    }
                }
            }
            channels.add(ch);
        }
        return channels;
    }

    public static void auto_run_channel(DRCDB drcdb){
        // String sqlstr="select channel_id,name,host_ip,port,protocol,data_type,type,channel4collect_id,path,filename,com,band_rate from channel";
        // sqlstr+=String.format(" where channel_id!=1 and enable=1");
        // record_data_set rds=drcdb.executeQuerySQL(sqlstr);
        // if(rds.datas.size()>0){
        //     for(int data_index=0;data_index<rds.datas.size();data_index++){
        //         switch(Integer.parseInt(rds.datas.get(data_index).get("protocol"))){
        //             case 1:
        //                 try {
        //                     DRModbus_TCP_Slave drm=new DRModbus_TCP_Slave(drcdb,Integer.parseInt(rds.datas.get(data_index).get("port")),Integer.parseInt(rds.datas.get(data_index).get("channel_id")));
        //                     // drm.bindPort(Integer.parseInt(rds.datas.get(data_index).get("port")));
        //                     drm.set_channel_type(
        //                         Integer.parseInt(rds.datas.get(data_index).get("type")),
        //                         Integer.parseInt(rds.datas.get(data_index).get("channel4collect_id")),
        //                         Integer.parseInt(rds.datas.get(data_index).get("data_type"))
        //                     );
        //                     drm.start();
        //                     channel_run_list.put("channel_"+rds.datas.get(data_index).get("channel_id"),drm);
        //                 } catch (Exception e) {
        //                     e.printStackTrace();
        //                 }
        //                 break;
        //             default:
        //         }
        //     }
        // }
        // 扫描服务通道列表
        // 根据是否启用判断是否启动该通道
        for(int i=1;i<channels.size();i++){
            channel ch=channels.get(i);
            if(ch.enable==1){
                // 根据协议类型启动服务通道
                switch(ch.protocol){
                    case 1:
                        try{
                            DRModbus_TCP_Slave drm=new DRModbus_TCP_Slave(drcdb,ch.port,ch.channel_id);
                            drm.set_channel_type(
                                ch.type,
                                ch.channel4collect_id,
                                ch.data_type
                            );
                            drm.start();
                            channel_run_list.put("channel_"+ch.channel_id,drm);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case 2:
                        try {
                            DRModbus_RTU_Slave drmr=new DRModbus_RTU_Slave(drcdb,ch.com,ch.band_rate,ch.parity,ch.stop,ch.channel_id);
                            drmr.set_channel_type(
                                    ch.type,
                                    ch.channel4collect_id,
                                    ch.data_type
                            );
                            drmr.start();
                            channel_run_list.put("channel_"+ch.channel_id,drmr);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }
        }
    }

    public static record_data_set defaultDataItems(){
        record_data_set rds=new record_data_set();
        List<String> columns=new ArrayList<String>();
        columns.add("data_index");
        columns.add("value1");
        columns.add("value2");
        columns.add("value3");
        columns.add("value4");
        rds.columns=columns;
        List<Map<String,String>> datas=new ArrayList<Map<String,String>>();
        for(int i=0;i<channel.data_count;i++){
            Map<String,String> row=new HashMap<String, String>();
            row.put("data_index",channels.get(0).dataItems.get(i).data_index+"");
            row.put("value1",channels.get(0).dataItems.get(i).value+"");
            row.put("value2",channels.get(0).dataItems.get(i+channel.data_count).value+"");
            row.put("value3",channels.get(0).dataItems.get(i+channel.data_count*2).value+"");
            row.put("value4",channels.get(0).dataItems.get(i+channel.data_count*3).value+"");
            datas.add(row);
        }
        rds.count=channel.data_count;
        rds.datas=datas;
        return rds;
    }

    @FJW_URI(value ="channel/defaultDataItemList")
    public static DRHTTP_API defaultDataItemList(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                record_data_set rds=defaultDataItems();
                content=record_data_set.get_answer_json_str(0,"",rds);
                return content;
            }
        };
    }

    @FJW_URI(value ="channel/runChannel")
    public static DRHTTP_API run_channel(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                String sqlstr="select channel_id,name,host_ip,port,protocol,path,filename,com,band_rate from channel";
                sqlstr+=String.format(" where channel_id=%s and enable=1",channel_id);
                record_data_set rds=drcdb.executeQuerySQL(sqlstr);
                if(rds.datas.size()>0){
                    switch(Integer.parseInt(rds.datas.get(0).get("protocol"))){
                        case 1:
                            try {
                                DRModbus_TCP_Slave drm=new DRModbus_TCP_Slave(drcdb,Integer.parseInt(rds.datas.get(0).get("port")),Integer.parseInt(rds.datas.get(0).get("channel_id")));
                                // drm.bindPort(Integer.parseInt(rds.datas.get(0).get("port")));
                                drm.start();
                                channel_run_list.put("channel_"+channel_id,drm);
                                content=dr_ajax_answer.sample_json_string(0,"线程启动！");
                            } catch (Exception e) {
                                content=dr_ajax_answer.sample_json_string(1,"启动失败！");
                                e.printStackTrace();
                            }
                            break;
                        default:
                    }
                }else{
                    content=dr_ajax_answer.sample_json_string(1,"错误操作，未找到该通道，或该通道停用");
                }
                return content;
            }
        };
    }

    @FJW_URI(value ="channel/stopChannel")
    public static DRHTTP_API stop_channel(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                String sqlstr="select channel_id,name,host_ip,port,protocol,path,filename,com,band_rate from channel";
                boolean result=false;
                sqlstr+=String.format(" where channel_id=%s",channel_id);
                record_data_set rds=drcdb.executeQuerySQL(sqlstr);
                if(rds.datas.size()>0){
                    if(channel_run_list.containsKey("channel_"+channel_id)){
                        Thread t=channel_run_list.get("channel_"+channel_id);
                        if(t.isAlive()){
                            t.interrupt();
                            channel_run_list.remove("channel_"+channel_id);
                            System.out.println(String.format("[%s]",rds.datas.get(0).get("protocol")));
                            if(rds.datas.get(0).get("protocol").equals("1")){
                                DRModbus_TCP_Slave drm=(DRModbus_TCP_Slave) t;
                                try {
                                    drm.releasePort();
                                    result=true;
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            if(result){
                                t=null;
                                System.gc();
                                content=dr_ajax_answer.sample_json_string(0,"通道已停止");                  
                            }else{
                                content=dr_ajax_answer.sample_json_string(1,"操作失败！");                  
                            }
                        }

                        // if(t.isInterrupted()){
                        // }else{
                        //     content=dr_ajax_answer.sample_json_string(1,"异常错误，通道未停止！");
                        // }
                    }else{
                        content=dr_ajax_answer.sample_json_string(1,"错误操作！！");
                    }            
                }

                return content;
            }
        };
    }

    public static void main(String[] args){
        DRCDB drcdb=new DRCDB();
        channel ch=new channel(drcdb);
        record_data_set rds=ch.read_channels();
        // for(Map<String, String> row:rds.datas){
        //     System.out.println(row.get("channel"));
        // }
        System.out.println(record_data_set.get_answer_json_str(0,"",rds));
    }
}